package com.year.shiyi.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.year.shiyi.common.utils.Result;
import com.year.shiyi.entity.from.SysLogin;
import com.year.shiyi.entity.mybatis.SysRoleEntity;
import com.year.shiyi.entity.mybatis.SysUserEntity;
import com.year.shiyi.service.*;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author shiyi
 */
@RestController
@RequestMapping
public class SysLoginController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private SysCaptchaService sysCaptchaService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysConfigService sysConfigService;

    /**
     * 验证码
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(response, uuid);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    @PostMapping("/sys/login")
    public Result<Object> login(@RequestBody SysLogin form) {
        // 是否开启了验证码
        if (sysConfigService.getCaptchaStatus()) {
            // 验证码是否有效
            if (!sysCaptchaService.validate(form.getUuid(), form.getCaptcha())) {
                return Result.fail("验证码已失效");
            }
        }
        SysUserEntity user = sysUserService.queryByUserName(form.getUsername());
//        String s = new Sha256Hash(form.getPassword(), user.getSalt()).toHex();
        if (user == null || !user.getPassword().equals(form.getPassword())) {
            return Result.fail("账号或者密码不正确");
        }
        // 账号锁定
        if(user.getStatus() == 1){
            return Result.fail("账号已被锁定,请联系管理员");
        }
        List<SysRoleEntity> roleEntities = sysRoleService.listRoleByUserId(user.getUserId());
        if (roleEntities == null ||roleEntities.size() == 0) {
            return Result.fail("无权限登录，请联系管理员配置角色");
        }
        return sysUserTokenService.createToken(user.getUserId());
    }


}
